﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Http;
using CoreApp.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using Aliyun.Acs.Core.Regions;
using System.Linq;
using CoreApp.Ali;
using CoreApp.Helper;

namespace CoreApp
{
    class Program
    {
        static string memberTemplateId = GetAppConfig("memberTemplateId");
        static string expertTemplateId = GetAppConfig("expertTemplateId");
        static string memberMobileTemplateId = GetAppConfig("memberMobileTemplateId");
        static string expertMobileTemplateId = GetAppConfig("expertMobileTemplateId");

        static void Main(string[] args)
        {
            //查询如果有在线咨询就关闭，如果有离线咨询专家已在线就改变状态为在线咨询并发送短信提醒
            string consulSql = "select id from consultation_userinfo where (consultation_type=1 or  consultation_type=2) and (consultation_status=1 or consultation_status=4)";
            List<int> Consulids= DbHelper.Query<int>(consulSql);
            if (Consulids.Count>0)
            {
                CoreFunction(Consulids);
            }
            //OffLineFunction();
        }

        #region 业务核心

        /// <summary>
        /// 在线咨询超时关闭及发送消息
        /// </summary>
        /// <param name="Consulids"></param>
        private static void CoreFunction(List<int> Consulids)
        {
            string sql = "select * from dbo.store_order where order_type=2 and union_id in(" + string.Join(",", Consulids) + ")";//查询所有正在咨询的订单
            List<dynamic> list = DbHelper.Query(sql);
            foreach (dynamic item in list)
            {
                int OrderId = item.id;
                int ConsulId = item.union_id;
                consultation_msg_temp msg = DbHelper.GetMsgForOrderId(OrderId);
                if (msg == null)
                {
                    DateTime otime = item.order_time;
                    TimeSpan ots = DateTime.Now - otime;
                    double ominute = ots.TotalMinutes;
                    if (ominute >= 30)
                    {
                        DbHelper.EndConsult(OrderId, ConsulId);
                        ConsulSendMsgMobile m = DbHelper.QueryMobileNumberByConsul(ConsulId);
                        if (!string.IsNullOrEmpty(m.memberPhoneNumber))
                        {
                            SendMobileMsg(m.memberPhoneNumber, false);
                        }
                        if (!string.IsNullOrEmpty(m.expertPhoneNumber))
                        {
                            SendMobileMsg(m.expertPhoneNumber, true);
                        }
                    }
                    continue;
                }
                TimeSpan ts = DateTime.Now - msg.msg_time;
                double minute = ts.TotalMinutes;
                if (minute >= 30)
                {
                    DbHelper.EndConsult(OrderId, ConsulId);
                    ConsulSendMsgMobile m = DbHelper.QueryMobileNumberByConsul(ConsulId);
                    if (!string.IsNullOrEmpty(m.memberPhoneNumber))
                    {
                        SendMobileMsg(m.memberPhoneNumber, false);
                    }
                    if (!string.IsNullOrEmpty(m.expertPhoneNumber))
                    {
                        SendMobileMsg(m.expertPhoneNumber, true);
                    }
                }
            }


            Console.WriteLine("End______________________________");
        }

        /// <summary>
        /// 离线咨询提交到未回复咨询中
        /// </summary>
        private static void OffLineFunction()
        {
            //offLine
            //先查所有离线咨询判断专家是否在线，一旦专家在线就修改咨询状态为未回复
            string OffSql = "select id,expert_id from consultation_userinfo where consultation_type=2 and consultation_status=5";//查询所有离线咨询
            List<dynamic> Offs = DbHelper.Query(OffSql);
            foreach (var item in Offs)
            {
                int expert_id = item.expert_id;
                if (CheckExpertOnline(expert_id))//Goto:判断专家是否在线
                {
                    int id = item.id;
                    DbHelper.SubmitOffConsult(id);
                }
            }
        }



        #endregion

        #region 帮助代码
        private static bool CheckExpertOnline(int ExpertId)
        {
            HttpHelper h = new HttpHelper();
            string json = h.HttpPostData("https://apicms.yla520.com/api/Consult/CheckExpertIsOnline", "{\"expertMemberId\":" + ExpertId + "}", "application/json");
            HttpRsModel<bool> rs = Newtonsoft.Json.JsonConvert.DeserializeObject<HttpRsModel<bool>>(json);
            return rs.data;
        }




        private async static void SendMobileMsg(string MobilePhone, bool IsExpert)
        {
            string TempletKey = memberMobileTemplateId;
            if (IsExpert)
            {
                TempletKey = expertMobileTemplateId;
            }
            var sms = new SmsObject
            {
                Mobile = MobilePhone,
                Signature = "有啦宝贝",
                TempletKey = TempletKey,
                Data = null,
                OutId = "OutId"
            };
            SendRs result = await new AliyunSmsSender("LTAI4cQpCKDfd9VH", "N5zwx4KvwEUOV4oZxLAaZNE5woi2gE").Send(sms);
            Console.WriteLine(result.success);
            Console.WriteLine(result.response);
            //if (!result.success)
            //{

            //}
            //if (!result.success) { out_data = GetHelper.dic_output_data(dic, result.response, false); return Ok(out_data); }
        }



        private static void SendTemplateMsg(string fromId, string openId, int memberType, object data)
        {
            string templateId = memberTemplateId;
            string page = "pages/yan";
            if (memberType == 2)
            {
                //待接受咨询提醒
                templateId = expertTemplateId;
                page = "pages/xi";
            }
            string WxAppId = "wx404eddb6dea0d0c0";
            string WxAppSecert = "5ce24950ea1d4fad9d50331f79583504";
            TokenResult token = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenResult>(TokenHelper.GetToken(WxAppId, WxAppSecert));
            string AccessToken = token.access_token;
            WxTemplateMessageHelper hp = new WxTemplateMessageHelper(AccessToken);
            string rs = hp.SendMsg(openId, fromId, page, templateId, data);
            Console.WriteLine(rs);
        }



        ///<summary> 
        ///返回*.exe.config文件中appSettings配置节的value项  
        ///</summary> 
        ///<param name="strKey"></param> 
        ///<returns></returns> 
        private static string GetAppConfig(string strKey)
        {
            string value = ConfigurationManager.AppSettings[strKey];
            return value;
        }



        #endregion

        #region 弃用代码
        //List<dynamic> list=DbHelper.Query(sql);
        //foreach (dynamic item in list)
        //{
        //    Console.WriteLine("正在处理订单:" + item.id);
        //    //查询该订单的第一次回复的消息的id，然后根据这个id查formid

        //    consultation_msg_temp  msg= DbHelper.GetMsgForOrderId(item.id);
        //    if (msg==null)
        //    {
        //        continue;
        //    }
        //    if (msg.msg_from_id==null)
        //    {
        //        continue;
        //    }
        //    if (msg.msg_to_id==null)
        //    {
        //        continue;
        //    }
        //    member_base from =DbHelper.GetMemberForId(msg.msg_from_id.Value);
        //    member_base to = DbHelper.GetMemberForId(msg.msg_to_id.Value);
        //    if (to.member_type==null)
        //    {
        //        continue;
        //    }
        //    //string openId = to.member_openid;

        //    weChatFormIds f =DbHelper.GetFormIds(msg.id);
        //    //专家不需要提醒
        //    if (!f.isUsed2&&to.member_type.Value!=2)
        //    {
        //        TimeSpan ts = DateTime.Now- msg.msg_time;
        //        if (ts.TotalMinutes>=3)//离当前时间超过3分钟
        //        {
        //            //专家应该不需要提醒
        //            object data = new
        //            {
        //                keyword1 = new WxTemplateMessageDataItem() { value = "当前咨询人数过多" },
        //                keyword2 = new WxTemplateMessageDataItem() { value = "有啦客服" },
        //                keyword3 = new WxTemplateMessageDataItem() { value = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") },
        //                keyword4 = new WxTemplateMessageDataItem() { value = "请耐心等待，如有不便之处，敬请谅解，感谢您对有啦的支持。" }
        //            };
        //            SendTemplateMsg(f.formId2, from.member_openid, to.member_type.Value,data);
        //            //把formId2 更新为已使用
        //            f.isUsed2 = true;
        //            DbHelper.UpdateFormIds(f);
        //        }
        //    }
        //    else if (!f.isUsed3)
        //    {
        //        //是否两个人都需要提醒
        //        //检查发送时间是否超过30分钟，如果超过自动关闭，需要判断发送的用户是专家以使用不同的模板使用不同的操作
        //        TimeSpan ts = DateTime.Now - msg.msg_time;
        //        if (ts.TotalMinutes>=30)
        //        {
        //            //需要关闭订单，并发送消息
        //            //EndOrder(id);
        //            //SendTemplateMsg(f.isUsed3,from)
        //            if (to.member_type.Value==2)//是发给专家的吗？
        //            {
        //                //发送给专家
        //                SendTemplateMsg(f.formId3,to.member_openid,to.member_type.Value, new
        //                {
        //                    keyword1 = new WxTemplateMessageDataItem() { value = from.member_realname },
        //                    keyword2 = new WxTemplateMessageDataItem() { value = msg.msg_text },
        //                    keyword3 = new WxTemplateMessageDataItem() { value = msg.msg_time.ToString("yyyy-MM-dd hh:mm:ss") },
        //                    keyword4 = new WxTemplateMessageDataItem() { value = "咨询超时，已关闭" }
        //                });
        //                //把formId3 更新为已使用
        //                //发送给咨询者
        //                SendTemplateMsg(f.formId4, from.member_openid, from.member_type.Value, new
        //                {
        //                    keyword1 = new WxTemplateMessageDataItem() { value = "有啦客服" },
        //                    keyword2 = new WxTemplateMessageDataItem() { value = "咨询超时" },
        //                    keyword3 = new WxTemplateMessageDataItem() { value = msg.msg_time.ToString("yyyy-MM-dd hh:mm:ss") },
        //                    keyword4 = new WxTemplateMessageDataItem() { value = "咨询超时已关闭" }
        //                });
        //                f.isUsed3 = true;
        //                f.isUsed4 = true;
        //                DbHelper.UpdateFormIds(f);

        //                //把formId4 更新为已使用
        //                DbHelper.EndConsult(item.id);
        //            }
        //            else
        //            {
        //                //发送给专家
        //                SendTemplateMsg(f.formId3, from.member_openid, from.member_type.Value, new
        //                {
        //                    keyword1 = new WxTemplateMessageDataItem() { value = from.member_realname },
        //                    keyword2 = new WxTemplateMessageDataItem() { value = msg.msg_text },
        //                    keyword3 = new WxTemplateMessageDataItem() { value = msg.msg_time.ToString("yyyy-MM-dd hh:mm:ss") },
        //                    keyword4 = new WxTemplateMessageDataItem() { value = "咨询超时，已关闭" }
        //                });
        //                //发送给咨询者
        //                SendTemplateMsg(f.formId3, to.member_openid, to.member_type.Value, new
        //                {
        //                    keyword1 = new WxTemplateMessageDataItem() { value = "有啦客服" },
        //                    keyword2 = new WxTemplateMessageDataItem() { value = "咨询超时" },
        //                    keyword3 = new WxTemplateMessageDataItem() { value = msg.msg_time.ToString("yyyy-MM-dd hh:mm:ss") },
        //                    keyword4 = new WxTemplateMessageDataItem() { value = "咨询超时已关闭" }
        //                });
        //                DbHelper.EndConsult(item.id);
        //            }
        //        }
        //    }
        //    Console.WriteLine("订单:" + item.id+"处理完成");
        //} 
        #endregion




    }
}
